﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace katOS
{
    class Scheduler
    {
        public volatile static Queue<Process> process_queue;
        Interpreter an_interpreter;
        volatile int pc; //process counter

        public Scheduler()
        { 
            process_queue = new Queue<Process>();
            an_interpreter = new Interpreter();
            pc = 1;
        }

        public void AddProcess(string file)
        {
            Process a_process = new Process(file, pc);
            Parser a_parser = new Parser(a_process,file);
            pc++;
            a_process.setInstructions(a_parser.getInstructionSet(a_process, a_process.getFileName()));
            process_queue.Enqueue(a_process);
        }

        public void ContextSwitch(int process_state)
        {
            process_queue.Peek().setState(process_state);
            process_queue.Enqueue(process_queue.Dequeue());
        }

        public void Run()
        {
            while (true)
            {
                if (process_queue.Count > 0)
                {
                    an_interpreter.To_Excecute(process_queue.Peek());
                }
                try
                {
                    if (process_queue.Peek().getState() == 5)
                    {
                        process_queue.Dequeue();
                    }
                }catch(InvalidOperationException){}
            }
        }

    }
}
